package map;

import java.util.*;

/**
 * 290. 单词规律
 */
public class WordPattern {
    public static boolean wordPattern(String pattern, String s) {
        int len = pattern.length();
        String[] str = s.split(" ");
        if (len != str.length) {
            return false;
        }
        // 双映射
        Map<Character, Integer> mapP = new HashMap<>();
        Map<String, Integer> mapS = new HashMap<>();
        StringBuilder strP = new StringBuilder();
        StringBuilder strS = new StringBuilder();
        int indexP = 0; // 翻译从0开始
        int indexS = 0;
        for (int i = 0; i < len; i++) {
            if (mapP.containsKey(pattern.charAt(i))) {
                strP.append(mapP.get(pattern.charAt(i)));
            } else {
                mapP.put(pattern.charAt(i), ++ indexP);
                strP.append(indexP);
            }
            if (mapS.containsKey(str[i])) {
                strS.append(mapS.get(str[i]));
            } else {
                mapS.put(str[i], ++ indexS);
                strS.append(indexS);
            }
        }
        return strP.toString().equals(strS.toString());
    }

    public static void main(String[] args) {
        String pattern = "abba";
        String s = "dog cat cat dog";
        System.out.println(wordPattern(pattern, s));
    }
}
